package com.financing.platform.web.api;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.AccessInfoDTO;
import com.financing.platform.dto.CorpProjectDTO;
import com.financing.platform.dto.FpBiddingReceiptDTO;
import com.financing.platform.dto.FpBiddingRevenueDTO;
import com.financing.platform.dto.FpProjectTransferHisDTO;
import com.financing.platform.dto.ProductAttachmentDTO;
import com.financing.platform.dto.ProductRecommendDTO;
import com.financing.platform.dto.ProjectAnnualRevenueDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.dto.ProjectExpandDTO;
import com.financing.platform.dto.ProjectRabateDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.ICompanyService;
import com.financing.platform.service.IFpBiddingReceiptService;
import com.financing.platform.service.IFpProjectTransferHisService;
import com.financing.platform.service.IProductRecommendService;
import com.financing.platform.service.IProjectAccountService;
import com.financing.platform.service.IProjectAnnualRevenueService;
import com.financing.platform.service.IProjectCommentsService;
import com.financing.platform.service.IProjectRabateService;
import com.financing.platform.service.IProjectRiskService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.DateUtil;
import com.financing.platform.util.Dict;
import com.financing.platform.util.MemcacheCacheHelper;
import com.financing.platform.util.PinyinUtil;
import com.financing.platform.util.StringUtil;

@Controller("projectUpdateActionApi")
@RequestMapping("/api/productUpdate")
@Scope("prototype")
public class ProjectUpdateAction extends BaseAction{
	
	@Autowired
	private IProjectService projectServiceImpl;
	
	@Autowired
	private IProjectAnnualRevenueService projectAnnualRevenueServiceImpl; 
	
	@Autowired
	private IProjectRabateService projectRabateSericeImpl;
	
	@Value("#{settings['groupId']}")
	private String groupId;
	
	@Autowired
	private IProjectCommentsService projectCommentsServiceImpl;
	
	@Autowired
	private IProjectRiskService projectRiskServiceImpl;
	
	@Autowired
	private IProductRecommendService productRecommendServiceImpl;
	
	@Autowired
	private ICompanyService companyServiceImpl;
	
	@Autowired
	private IProjectAccountService projectAccountServiceImpl;
	
	@Autowired
	private IFpProjectTransferHisService fpProjectTransferHisService;
	
	@Autowired
	private IFpBiddingReceiptService biddingReceiptService;
	
	/**
	 * 
	* @Title: queryUpdateProjectList 
	* @Description: 产品列表
	* @param   request
	* @param   response
	* @param   projectDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUpdateProjectList.shtml")
	@ResponseBody
	public ResultMap queryUpdateProjectList(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		try{
			if(projectDTO.getPageNo() == null){
				projectDTO.setPageNo(1);
			}
			if(projectDTO.getPageSize() == null){
				projectDTO.setPageSize(20);
			}
			UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			if(!user.getUserNickname().equals("admin")){
				projectDTO.setCreateBy(user.getUsername());
			}
			Integer count = projectServiceImpl.projectListForPublishCount(projectDTO);
			projectDTO.setTotalCount(count);
			projectDTO.setPageCount(count%projectDTO.getPageSize() == 0 ? count/projectDTO.getPageSize():count/projectDTO.getPageSize()+1);
			List<ProjectDTO> projectList =  projectServiceImpl.queryAllProject(projectDTO);
			resultMap.setAttribute("projectList", projectList);
			resultMap.setAttribute("projectDTO", projectDTO);
		 	resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryUpdateProjectList error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	/**
	 * 
	* @Title: queryUpdateProject 
	* @Description: 产品详情
	* @param   request
	* @param   response
	* @param     projectDTO
	* @return ModelAndView   
	* @throws
	 */
	@RequestMapping("/queryUpdateProject.shtml")
	@ResponseBody
	public ResultMap queryUpdateProject(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		 try{
			ProjectDTO project =  projectServiceImpl.queryProject(projectDTO);
			resultMap.setAttribute("project", project);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("queryUpdateProject error !",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	/**
	 * 
	* @Title: updateProjectBaseInfo 
	* @Description: 更新产品
	* @param   request
	* @param     projectDTO
	* @throws
	 */
	@RequestMapping("/updateProjectBaseInfo.shtml")
	@ResponseBody
	public ResultMap updateProjectBaseInfo(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO) {

		log.info("in updateProjectBaseInfo begin!");
		try {

			//批量  更新
			if(StringUtils.isNotBlank(projectDTO.getIds()) && projectDTO.getId() == null){
				DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
				projectServiceImpl.updateProject(projectDTO);
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
				return  resultMap;
			}


			//判断是否有权限修改产品
			if(!isAccess(projectDTO.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			
			projectExpandDTO.setpId(projectDTO.getId());
			DTOdateSet.setUpdateInfo(projectExpandDTO, request.getSession());
			
			projectDTO.setpExpectSubscriptionAmount(projectDTO.getpIssuingScale());
			if(projectDTO.getpIssuingScale() != null){
				projectDTO.setpIssuingScale(projectDTO.getpIssuingScale());
			}
			if(projectDTO.getpIssuingScale() != null){
				projectDTO.setpIssuingScale(projectDTO.getpIssuingScale());
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionShare(projectDTO.getpExpectSubscriptionAmount());
			}
			if(projectDTO.getpMinimumAmount() != null){
				projectDTO.setpMinimumAmount(projectDTO.getpMinimumAmount());
			}
			if(projectDTO.getpExpectSubscriptionAmount() != null){
				projectDTO.setpExpectSubscriptionAmount(projectDTO.getpExpectSubscriptionAmount());
			}
			if(projectDTO.getpProgressiveAmount() != null){
				projectDTO.setpProgressiveAmount(projectDTO.getpProgressiveAmount());
			}
			projectDTO.setpImageUri(request.getParameter("image"));
			projectDTO.setpPublicStatus(null);
			projectDTO.setStatus(null);
			
			//赋值搜索字段
			try {
				projectDTO.setpSearchName(projectDTO.getpName()+PinyinUtil.convert(projectDTO.getpName()));
			} catch (Exception e) {
				log.error("PinyinUtil.convert(projectDTO.getpName()) error!",e);
			}
			
			
			DTOdateSet.setUpdateInfo(projectExpandDTO, request.getSession());
			DTOdateSet.setCreateInfo(projectExpandDTO, request.getSession());
			projectServiceImpl.updateProjectFull(projectDTO,projectExpandDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("update project error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("in updateProjectBaseInfo end!");
		return resultMap;
	}
	
	@RequestMapping("/queryProjectAttachments.shtml")
	@ResponseBody
	public ResultMap queryProjectAttachments(Integer pId){
		try {
			resultMap.setAttribute("projectAttachmentsList", projectServiceImpl.queryProductAttachments(pId));
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("query project attachments error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}
	
	@RequestMapping("/updateProjectAttachments.shtml")
	@ResponseBody
	public ResultMap updateProjectAttachments(HttpServletRequest request,Integer pId){
		try{
			
			//判断是否有权限修改产品
			if(!isAccess(pId,request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			
			String[]  productAttachementFileType = request.getParameter("fileType").split("[,]");
			String[]  productAttachementFileName = request.getParameter("fName").split("[,]");
			String[]  productAttachementFilePath = request.getParameter("fileUrl").split("[,]");
			List<ProductAttachmentDTO> productAttachmentDTOList = new ArrayList<ProductAttachmentDTO>() ;
			
			if(productAttachementFileName != null && productAttachementFileType != null && productAttachementFilePath != null && productAttachementFileName.length == productAttachementFileType.length && productAttachementFileType.length == productAttachementFilePath.length){
				for(int i = 0 ; i< productAttachementFileName.length; i++){
					  if(productAttachementFilePath[i].trim().length()>0){
						  ProductAttachmentDTO productAttachmentDTO = new ProductAttachmentDTO();
						  productAttachmentDTO.setfName(productAttachementFileName[i]);
		                  productAttachmentDTO.setfUploadTime(new Date());
		                  productAttachmentDTO.setfType(productAttachementFileType[i]);
		                  productAttachmentDTO.setfPath(productAttachementFilePath[i]);
		                  
		                  productAttachmentDTOList.add(productAttachmentDTO);
					  }
				}
			}
			projectServiceImpl.updateProductAttachment(productAttachmentDTOList, pId);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("update project Attachments error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	
	
	@RequestMapping("/queryUpdateProjectAnnualRevenue.shtml")
	@ResponseBody
	public ResultMap queryUpdateProjectAnnualRevenue(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		try{
			List<ProjectAnnualRevenueDTO> projectAccount =  projectAnnualRevenueServiceImpl.queryProjectAnnualRevenue(projectDTO.getId());
			ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
			projectRabateDTO.setpId(projectDTO.getId());
			List<ProjectRabateDTO> projectRabateList  = projectRabateSericeImpl.queryProjectRabate(projectRabateDTO);
			
			//获取当前用户是否有查看核心价的权限
			UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
			List<AccessInfoDTO> accessInfoList = user.getAccessList();
			boolean accessFlag = false;
			if(accessInfoList == null && user.getUserNickname().equals("admin")){
				accessFlag = true;
			}else if(accessInfoList != null ){
				for(AccessInfoDTO accessInfo : accessInfoList){
					if(groupId.equals(accessInfo.getGroupId())  || isAccess(projectDTO.getId(), request)){
						accessFlag = true;
						projectDTO.setTarget(1);
						break;
					}else{
						projectDTO.setTarget(0);
					}
				}
			}
			
			//如果没有核心价查看权限 则去掉核心价
			if(!accessFlag){
				for(ProjectRabateDTO projectRabate : projectRabateList){
					projectRabate.setpCorePrice(null);
					projectRabate.setpCoreBackPrice(null);
					
				}
			}
			
			//查询竞价列表   设置竞价
			FpBiddingReceiptDTO dto=new FpBiddingReceiptDTO();
			dto.setpId(projectDTO.getId());
			List<Map<String, Object>> queryBiddingReceiptSuccessRebate = biddingReceiptService.queryBiddingReceiptSuccessRebate(dto);
			if(queryBiddingReceiptSuccessRebate!=null&&queryBiddingReceiptSuccessRebate.size()>0){
				for (int i=0;i<projectRabateList.size();i++) {
					try {
						BigDecimal pRebateAmount=new BigDecimal(queryBiddingReceiptSuccessRebate.get(i).get("pRebateAmount")+"");
						projectRabateList.get(i).setpRebateAmount(pRebateAmount);
					} catch (Exception e) {
						log.error("queryBiddingReceiptSuccessRebate set rebate error ",e);
					}
				}
			}
			
			
			CorpProjectDTO	corpProjectDTO = projectServiceImpl.queryCorpProject(projectDTO.getId());
			resultMap.setAttribute("projectAnnualRevenue", projectAccount);
			resultMap.setAttribute("project", projectDTO);
			resultMap.setAttribute("projectRabateList", projectRabateList);
			resultMap.setAttribute("corpProjectDTO", corpProjectDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryUpdateProjectAnnualRevenue error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		
		return resultMap;
	}
	
	@RequestMapping("/updateProjectAnnualRevenue.shtml")
	@ResponseBody
	public ResultMap updateProjectAnnualRevenue(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		 try{
			String[] projectId = request.getParameter("pId").split("[,]");
			String[] pAnnualRevenueExpect = request.getParameter("pAnnualRevenueExpect").split("[,]");
			String[] pStartAmount = request.getParameter("pStartAmount").split("[,]");
			String[] pEndAmount =request.getParameter("pEndAmount").split("[,]");
			String[] pRabateType = request.getParameter("pRebateType").split("[,]");
			String[] pRabateProfit = request.getParameter("pRabateProfit").split("[,]");
			String[] pSellingPrice = request.getParameter("pSellingPrice").split("[,]");
			String[] pCostPrice = request.getParameter("pCostPrice").split("[,]");
			String[] pCorePrice = request.getParameter("pCorePrice").split("[,]");
			String[] pIsAgreement = request.getParameter("pIsAgreement").split("[,]");
			String[] pCostBackPrice = request.getParameter("pCostBackPrice").split("[,]");
			String[] pCoreBackPrice = request.getParameter("pCoreBackPrice").split("[,]");
			String[] pBackSellingPrice = request.getParameter("pBackSellingPrice").split("[,]");
			String[] pBackRabateProfit = request.getParameter("pBackRabateProfit").split("[,]");
			
			ProjectDTO project = new ProjectDTO();
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setId(projectDTO.getId());
			projectTmp.setStatus(Dict.pProductStatus_need_Verify);
			projectTmp.setpPublicStatus(Dict.pPublicStatus_No_public);
			DTOdateSet.setUpdateInfo(projectTmp, request.getSession());
			
			//判断是否有权限修改产品
			if(!isAccess(projectDTO.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			projectAnnualRevenueServiceImpl.deleteProjectAnnualRevenue(projectDTO.getId());
			projectRabateSericeImpl.deleteProjectRabate(projectDTO.getId());
			
			for(int i = 0;i<projectId.length; i++){
				
				project.setId(projectDTO.getId());
				
				project = projectServiceImpl.queryProject(project);
				if(project.getId() == null){
					continue;
				}
				
				ProjectAnnualRevenueDTO projectAnnualRevenueDTO = new ProjectAnnualRevenueDTO();
				ProjectRabateDTO projectRabateDTO = new ProjectRabateDTO();
				
				projectAnnualRevenueDTO.setpAnnualRevenueExpect(pAnnualRevenueExpect[i]);
				projectAnnualRevenueDTO.setpStartAmount(new BigDecimal(pStartAmount[i]));
				projectAnnualRevenueDTO.setpEndAmount(new BigDecimal(pEndAmount[i]));
				projectAnnualRevenueDTO.setpId(Integer.valueOf(projectId[i]));
				if(pRabateType != null && pRabateType.length > 0){
					projectRabateDTO.setpRabateProfit(new BigDecimal(pRabateProfit[i]));
					projectRabateDTO.setpRabateType(pRabateType[i]);
					projectRabateDTO.setpId(Integer.valueOf(projectId[i]));
					//销售价格
					projectRabateDTO.setpSellingPrice(new BigDecimal(pSellingPrice[i]));
					//核心价格
					projectRabateDTO.setpCorePrice(new BigDecimal(pCorePrice[i]));
					//成本价格
					projectRabateDTO.setpCostPrice(new BigDecimal(pCostPrice[i]));
					//后端挂网价
					projectRabateDTO.setpBackRabateProfit(new BigDecimal(pBackRabateProfit[i]));
					//后端机构价
					projectRabateDTO.setpBackSellingPrice(new BigDecimal(pBackSellingPrice[i]));
					//后端成本价
					projectRabateDTO.setpCostBackPrice(new BigDecimal(pCostBackPrice[i]));
					//后端核心价
					projectRabateDTO.setpCoreBackPrice(new BigDecimal(pCoreBackPrice[i]));
					
					//是否协议
					projectRabateDTO.setpIsAgreement(pIsAgreement[i]);
					DTOdateSet.setCreateInfo(projectRabateDTO, request.getSession());
					DTOdateSet.setUpdateInfo(projectRabateDTO, request.getSession());
				}
				
				DTOdateSet.setCreateInfo(projectAnnualRevenueDTO, request.getSession());
				DTOdateSet.setUpdateInfo(projectAnnualRevenueDTO, request.getSession());
				
				int arId = projectAnnualRevenueServiceImpl.insertProjectAnnualRevenue(projectAnnualRevenueDTO);
				if(pRabateType != null && pRabateType.length > 0){
					projectRabateDTO.setArId(arId);
					projectRabateSericeImpl.addProjectRabateInfo(projectRabateDTO);
				}
			}
			
			//价格修改通知
			try {
				ProjectDTO p = new ProjectDTO();
				p.setId(projectDTO.getId());
				 p = projectServiceImpl.queryProject(p);
				Boolean flagBaoxiao = p.getFlagBaoxiao();
				//分销已发布产品  修改价格  变动通知
				if((flagBaoxiao==null||!flagBaoxiao)&&"02,03".contains(p.getpType())&&Dict.pPublicStatus_Yes_public.equals(p.getpPublicStatus())){
					Map<Integer,Date> updateProductIdMap =	(Map<Integer, Date>) MemcacheCacheHelper.mcc.get("updateProductIdMap");
					if(updateProductIdMap!=null){
						Date date = updateProductIdMap.get(projectDTO.getId());
						//  获取第一次修改 处理
						if(date==null){
							updateProductIdMap.put(projectDTO.getId(), new Date());
							MemcacheCacheHelper.mcc.set("updateProductIdMap",updateProductIdMap);
						}else{
							//存在不处理
						}
					}else{
						HashMap<Integer, Date> hashMap = new HashMap<Integer,Date>();
						hashMap.put(projectDTO.getId(), new Date());
						MemcacheCacheHelper.mcc.set("updateProductIdMap",hashMap);
					}
				}
			} catch (Exception e) {
				log.error("MemcacheCacheHelper updateProductIdMap error!",e);
			}
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("updateProjectAnnualRevenue error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	@RequestMapping("/deleteProject.shtml")
	@ResponseBody
	public ResultMap deleteProject(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO){
		try{
			//判断是否有权限删除产品
			if(!isAccess(projectDTO.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			
			projectDTO.setpPublicStatus(Dict.pPublicStatus_No_public);
			projectDTO = projectServiceImpl.queryProject(projectDTO);
			if(projectDTO != null && projectDTO.getId() != null ){
				projectAccountServiceImpl.deleteProjectAccount(projectDTO.getId());
				projectAnnualRevenueServiceImpl.deleteProjectAnnualRevenue(projectDTO.getId());
				projectRabateSericeImpl.deleteProjectRabate(projectDTO.getId());
				projectServiceImpl.deleteProject(projectDTO.getId());
				ProductRecommendDTO productRecommendDto = new ProductRecommendDTO();
				productRecommendDto.setFpProjectId(projectDTO.getId());
				productRecommendServiceImpl.deleteProductRecommend(productRecommendDto);
				projectRiskServiceImpl.deleteProjectRisk(projectDTO.getId());
			}	
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("delete project info error ",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	/**
	 * 
	 * @Title: changepRecruitmentSummary
	 * @Description: 修改募集进度 
	 * @param @param request
	 * @param @param response
	 * @param @param projectDTO
	 * @param @return   
	 * @return ResultMap   
	 * @throws
	 */
	@RequestMapping("/changepRecruitmentSummary.shtml")
	@ResponseBody
	public ResultMap changepRecruitmentSummary(HttpServletRequest request,HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO){
		try{
			//判断是否有权限修改产品
			if(!isAccess(projectDTO.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			ProjectDTO projectTmp = new ProjectDTO();
			projectTmp.setId(projectDTO.getId());
			projectTmp.setpRecruitmentSummary(projectDTO.getpRecruitmentSummary());
			projectTmp.setStatus(Dict.pProductStatus_need_Verify);
			projectTmp.setpPublicStatus(Dict.pPublicStatus_No_public);
			projectServiceImpl.updateProject(projectDTO,projectExpandDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}catch(Exception e){
			log.error("changepRecruitmentSummary error :",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	
	/**
	 * 判断要修改的产品是否为当前用户所有
	 * @param projectId
	 * @param request
	 * @return
	 */
	private boolean isAccess(int projectId,HttpServletRequest request){
		
		UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
		
		//超级管理员具有所有产品的管理权限
		if(user.getUsername().equals("admin")){
			return true;
		}
		//权限扭转接收人
		FpProjectTransferHisDTO dto = new FpProjectTransferHisDTO();
		dto.setPProjectId(projectId);
		dto.setpProjectType("01");//“01：信托，资管，PEVC” 
		String createBy = fpProjectTransferHisService.getTransferUserNameByProjectID(dto);
		if(!StringUtil.isNullOrEmptyStr(createBy)){
			//是否是扭转接收人
			if(user.getUsername().equals(createBy)){
				return true;
			}else{
				return false;
			}
		}

		
		ProjectDTO p = new ProjectDTO();
			p.setId(projectId);
			 p = projectServiceImpl.queryProject(p);
			 if(p!=null && p.getCreateBy().equals(user.getUsername())){
				 return true;
			 }
		return false;
	}
	
	
	/**
	 * 修改产品（修改版）
	 * @param request
	 * @param response
	 * @param projectDTO 产品基本信息
	 * @param projectExpandDTO 产品扩展信息
	 * @return
	 */
	@RequestMapping("/updateProduct.shtml")
	@ResponseBody
	public ResultMap updateProduct(HttpServletRequest request,
			HttpServletResponse response,ProjectDTO projectDTO,ProjectExpandDTO projectExpandDTO) {
		
			log.info("in updateProduct begin!");
		try {
			
			//判断是否有权限修改产品
			if(!isAccess(projectDTO.getId(),request)){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_NO_ACCESS);
				return resultMap;
			}
			
			//数据初始化
			DTOdateSet.setUpdateInfo(projectDTO, request.getSession());
			projectExpandDTO.setpId(projectDTO.getId());
			DTOdateSet.setUpdateInfo(projectExpandDTO, request.getSession());
			projectDTO.setpExpectSubscriptionAmount(projectDTO.getpIssuingScale());
			//防止状态被改
			projectDTO.setpPublicStatus(null);
			projectDTO.setStatus(null);

			//赋值搜索字段
			try {
				projectDTO.setpSearchName(projectDTO.getpName()+PinyinUtil.convert(projectDTO.getpName()));
			} catch (Exception e) {
				log.error("PinyinUtil.convert(projectDTO.getpName()) error!",e);
			}
			
			projectServiceImpl.updateProduct(projectDTO,projectExpandDTO);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			
			log.info("in updateProduct end!");
		} catch (Exception e) {
			log.error("update project error!",e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		return resultMap;
	}
	public static void main(String[] args) {
		System.out.println("lisu新股测试"+PinyinUtil.convert("lisu新股测试"));
	}
}

